package com.gushi.util.excel;

import com.gushi.JavaLearn.report.rowClass.rcStudent;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;

public class gsExcel {

    public static void writeExcel (Object[] array, String path) {

        Field[] fields = array.getClass().getComponentType().getDeclaredFields();

        //获取合适的列名数组
        String[] colNames = new String[fields.length];
        for (int i = 0; i < colNames.length; ++i) {
            Field curField = fields[i];
            anttnExcelColumn anttn = curField.getDeclaredAnnotation(anttnExcelColumn.class);
            if (anttn != null) {
                colNames[i] = anttn.name();
            }
            else {
                colNames[i] = curField.getName();
            }
        }

        HSSFWorkbook workbook = new HSSFWorkbook();
        Sheet sheet = null;
        anttnExcelSheet anttnSheet = array.getClass().getComponentType().getAnnotation(anttnExcelSheet.class);
        if (anttnSheet != null) {
            sheet = workbook.createSheet(anttnSheet.name());
        }
        else {
            sheet = workbook.createSheet();
        }

        Row headRow = sheet.createRow(0);
        for (int x = 0; x < colNames.length; ++x) {
            Cell cell = headRow.createCell(x);
            cell.setCellValue(colNames[x]);
        }

        for (int y = 1; y < array.length + 1; ++y) {

            Object curObj = array[y - 1];
            Row curBodyRow = sheet.createRow(y);
            Field[] curObjFields = curObj.getClass().getDeclaredFields();

            for (int x = 0; x < curObjFields.length; ++x) {

                Field curField = curObjFields[x];
                curField.setAccessible(true);

                String value = new String();
                try {
                    value = curField.get(curObj).toString();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

                Cell cell = curBodyRow.createCell(x);
                cell.setCellValue(value);
            }
        }


        try {
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            workbook.write(fileOutputStream);
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
